<template>
  <div class="container">
    <!-- 搜索区 -->
    <a-form
      :model="searchForm"
      label-align="left"
      layout="inline"
      auto-label-width
      class="search-area"
    >
      <a-form-item
        field="name"
        label="团队名称"
        label-col-flex="auto"
        content-class="item"
      >
        <a-input
          v-model="searchForm.name"
          placeholder="请输入"
          allow-clear
          @change="handleSearch"
        />
      </a-form-item>
    </a-form>

    <a-divider margin="4px 0 24px" />

    <list-title title-text="团队列表" btn-text="添加团队" @add="handleAdd" />

    <div class="table-container">
      <a-table
        :loading="loading"
        :columns="teamColumns"
        :data="teamList"
        :scroll="{ x: '100%', y: '100%' }"
        :bordered="false"
        :pagination="pagination"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #name="{ record }">
          <div class="name-column">
            <a-trigger
              :popup-visible="record.isShowColor"
              trigger="click"
              :unmount-on-close="false"
              :popup-translate="[94, -8]"
              update-at-scroll
              @popup-visible-change="handleColorVisibleChange($event, record)"
            >
              <div class="icon-container">
                <span
                  class="normal-icon"
                  :class="{
                    'active-icon': record.isShowColor,
                  }"
                  :style="{ backgroundColor: record.color }"
                ></span>
              </div>
              <template #content>
                <color-select
                  :init-color="record.color"
                  @color-changed="handleColorChanged($event, record)"
                />
              </template>
            </a-trigger>
            <span class="name-text">{{ record.name }}</span>
          </div>
        </template>
        <template #count="{ record }">
          <span>{{ record.count }}</span>
        </template>
        <template #operations="{ record }">
          <a-button
            type="text"
            size="small"
            @click="handleOperation(record, 'view')"
            >查看</a-button
          >
          <a-button
            type="text"
            size="small"
            @click="handleOperation(record, 'edit')"
            >编辑
          </a-button>
        </template>
      </a-table>
    </div>

    <add-team
      v-model:visible="addDialogVisible"
      :form="addTeamInfo"
      @refresh="handleSearch"
    />
    <team-info-dialog
      v-model:visible="editDialogVisible"
      :origin-data="editTeamInfo"
      :handle-type="handleType"
      @refresh="handleSearch"
    />
  </div>
</template>

<script lang="ts" setup>
  import { computed, reactive, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import useLoading from '@/hooks/loading';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { Message } from '@arco-design/web-vue';
  import { TeamRecord, queryTeamList, updateTeam } from './api';
  import ListTitle from '../components/list-title.vue';
  import AddTeam from './components/add-team.vue';
  import colorSelect from './components/color-select.vue';
  import TeamInfoDialog from './components/edit-team.vue';
  import colors from './json/colors.json';

  const route = useRoute();
  const projectId = computed(() => {
    return String(route?.params?.projectId);
  });

  // 新增
  const addDialogVisible = ref(false);
  const emptyTeam: TeamRecord = {
    projectId: projectId.value,
    name: '',
    color: '',
    role: 1,
    count: 0,
    teamUsers: [],
    userIds: '',
  };
  const addTeamInfo = ref<TeamRecord>({ ...emptyTeam });

  // 查看/编辑
  const editDialogVisible = ref(false);
  const handleType = ref('view');
  const editTeamInfo = ref<TeamRecord>({ ...emptyTeam });

  // 搜索栏
  const searchForm = reactive<any>({
    name: '',
  });

  // 列表
  const { loading, setLoading } = useLoading(true);
  const teamColumns = computed<TableColumnData[]>(() => [
    {
      title: '序号',
      dataIndex: 'index',
      slotName: 'index',
      align: 'center',
      width: 62,
    },
    {
      title: '团队名称',
      dataIndex: 'name',
      slotName: 'name',
      bodyCellClass: 'link-text',
    },
    {
      title: '成员人数',
      dataIndex: 'count',
      slotName: 'count',
      align: 'center',
      bodyCellClass: 'link-text',
      width: 238,
    },
    {
      title: '操作',
      slotName: 'operations',
      align: 'center',
      width: 180,
    },
  ]);

  const pagination = reactive({
    showTotal: true,
    showPageSize: true,
    showJumper: true,
    pageSize: 10,
    current: 1,
    total: 0,
  });

  const teamList = ref([]);

  // 查询列表数据
  const getTeamList = () => {
    setLoading(true);
    const params: any = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      projectId: projectId.value,
    };
    Object.keys(searchForm).forEach((key) => {
      if (searchForm[key]) {
        params[key] = searchForm[key];
      }
    });
    queryTeamList(params)
      .then((res) => {
        teamList.value = res.data.list || [];
        pagination.total = res.data.total;
        teamList.value.forEach((team: TeamRecord) => {
          team.isShowColor = false;
        });
      })
      .catch((err) => {
        // eslint-disable-next-line no-console
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const handleSearch = () => {
    pagination.current = 1;
    getTeamList();
  };

  // 新增按钮点击事件
  const handleAdd = () => {
    // 设置新增的团队颜色
    const colorIndex = pagination.total % colors.length;
    addTeamInfo.value = { ...emptyTeam, color: colors[colorIndex] };
    addDialogVisible.value = true;
  };

  // 查看/编辑按钮点击事件
  const handleOperation = (record: TeamRecord, operation: string) => {
    handleType.value = operation;
    editTeamInfo.value = { ...record };
    editDialogVisible.value = true;
  };

  // 选择颜色面板显示隐藏处理
  const handleColorVisibleChange = (visible: boolean, record: TeamRecord) => {
    record.isShowColor = visible;
  };

  // 调用接口修改团队颜色
  const handleColorChanged = async (nValue: string, record: TeamRecord) => {
    const params = {
      ...record,
      color: nValue,
    };
    delete params.isShowColor;
    const res = await updateTeam(params);
    if (res.status) {
      Message.success('编辑成功');
      record.isShowColor = false;
      record.color = nValue;
    }
  };

  // 页码改变事件处理
  const handlePageChange = (page: number) => {
    pagination.current = page;
    getTeamList();
  };

  // 每页条数改变事件处理
  const handlePageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    getTeamList();
  };

  getTeamList();
</script>

<style scoped lang="less">
  .container {
    height: calc(100vh - 156px);
  }
  .search-area {
    padding: 8px 0 4px 0;

    :deep(.item) {
      width: 220px;
    }
  }

  .table-container {
    height: calc(100% - 129px);
  }

  .name-column {
    display: flex;
    align-items: center;

    .icon-container {
      display: flex;
      justify-content: center;
      width: 54px;

      .normal-icon {
        display: inline-block;
        width: 20px;
        height: 20px;
        border-radius: 50%;
      }

      .active-icon {
        box-shadow: 0px 2px 5px 0px #e5e6eb;
        border: 2px solid #ffffff;
        width: 24px;
        height: 24px;
      }
    }

    .name-text {
      margin-left: 16px;
    }
  }

  .link-text {
    span {
      color: #3366ff;
    }
  }
</style>
